/**
 * @author Jacye.Ouyang
 */
var RTQ_ChartUtil  = {
	formatDate:function(date) {     //formate date to yyyy-mm-dd
        if (date == null) {
            return null;
        }
        return date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate(); 
    },  
	formatDateMDY:function(date,line) {     //formate date to yyyy-mm-dd
        if (date == null) {
            return null;
        }
		var l = line;
		if(typeof(line)=="undefined"){
			l="-";
		}
        return  ((date.getMonth()+1)<=9?"0":"")+(date.getMonth() + 1) + "-" +(date.getDate()<=9?"0":"")+ date.getDate()+ "-" + date.getFullYear(); 
    },		
	formatDateToVBDate:function(date){//format date to mm/dd/yyyy.
		if(date == null){
            return null;
        }
        return (date.getMonth() + 1) + "/" + date.getDate()+ "/" + date.getFullYear(); 
	},
	convertToDate:function(d) {    // convert yy-mm-dd to date format.
        if (d == null || d =="") {
            return null;
        }
        var f = d.split('-');
		if(f.length>1){
			var f1 = f[0], f2 = parseInt(f[1], 10), f3 = parseInt(f[2], 10);
            return new Date(f1, f2 - 1, f3);
		}else{
			var f1 =parseInt(d.substr(0,4), 10), f2 = parseInt(d.substr(4,2), 10), f3 = parseInt(d.substr(6,2), 10);
            return new Date(f1, f2 - 1, f3);
		}
        
    },
	convertToVBDate:function(d){  // convert mm/dd/yyyy to date format.
		if (d == null || d =="") {
            return null;
        }
        var f = d.split('/');
        var f1 = f[2], f2 = parseInt(f[0], 10), f3 = parseInt(f[1], 10);
        return new Date(f1, f2 - 1, f3);
	},
	compareDate:function(from, to) {  // comapair the date (mm/dd/yyyy)
        var f = from.split('/'), t = to.split('/'),  f1 = f[2],  f2 = parseInt(f[0], 10), f3 = parseInt(f[1], 10);
        var  t1 = t[2],  t2 = parseInt(t[0], 10),   t3 = parseInt(t[1], 10);     
        return  f1<t1? true:(f1 == t1?(f2 < t2?true:(f2 == t2?(f3 < t3?true:false):false)):false);
    },
	compareDateByday:function(from,to){  // is the same day.
	    if(!from||!to) return false;
		var s = new Date(from.getFullYear(),from.getMonth(),from.getDate());
		var e = new Date(to.getFullYear(),to.getMonth(),to.getDate());
		return e.getTime()==s.getTime();
	},
    isVbDate:function(str) { //check the date format mm-dd-yyyy or mm/dd/yyy or mm.dd.yyyy.
         var reg = /^(\d{1,2})(-|\/|\.)(\d{1,2})\2(\d{4})$/;
         var result = str.match(reg);
         if (result == null) return false; 
         var y, m, d;
         y = result[4]; //year number
         m = parseInt(result[1], 10); //month number
         d = parseInt(result[3], 10); //day 
         if ((m < 1) || (m > 12) || (d < 1) || (d > 31)) return false;
         if (((m == 4) || (m == 6) || (m == 9) || (m == 11)) && (d > 30)) return false;
         if ((y % 4) == 0) {
            if ((m == 2) && (d > 29)) return false;
         } else {
            if ((m == 2) && (d > 28)) return false;
         }
         return true;
    },
	trimDate:function(date) { 
        return new Date(date.getFullYear(), date.getMonth(), date.getDate());
    },
    toDateIndex:function(dt) { // days from 1900-1-1;
        if (dt == null) {
            return 0;
        }
        var st = new Date(1900, 0, 1).getTime(); 
        var end= new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()).getTime();
        return (end-st)/86400000;   //(24 * 60 * 60 * 1000)=86400000
    },
    toDateFromIndex:function(index) {   // must use new Date(1900,0,1) Notice Zone difference.
        return new Date (index* 86400000 + new Date(1900,0,1).getTime());//(24 * 60 * 60 * 1000)=86400000  -2209017600000 = 
    },
	toDateFromIndexOrTick:function(v,type){
		if(type==0){
			return new Date(v);
		}else{
			return this.toDateFromIndex(v);
		}
	},
	formatPChartXLabel:function(tick,type,isIntradayTimSyle){
		if(tick==null) return "";
		var t =  parseInt(tick,10),dt;
        if (type == 1||isIntradayTimSyle) {  // one day chart
        	dt = new Date(t);
            return dt==null?"":QS_DateFmt.getTimeString(dt);
        }else if (type == 2||type == 0) {
			dt = new Date(t);
			return dt==null?"":this.formatDateToWeekMMDD(dt);
		}else {
			dt = new Date (t* 86400000+new Date(1900,0,1).getTime());
			return dt==null?"":QS_DateFmt.getDateString(dt);
		}
	},
	formatDateToWeekMMDD:function(d){  // www mm dd.
		return QS_DateFmt.getWeekDay(d)+" "+QS_DateFmt.getMonthDate(d);
	},
	formatSChartXLabel:function(tick,freq){
		if(tick==null) return "";
		var t =  parseInt(tick,10);
        var dt =  new Date (t* 86400000+new Date(1900,0,1).getTime());
		if(freq=="minute"){
			return dt==null?"":QS_DateFmt.Mo[dt.getMonth()];
		} else if (freq == "d") {
            return dt==null?"":dt.getFullYear(); //DTFormat.ToShortYearMonth(dt);
        } else {
            return dt==null?"":dt.getFullYear().toString().substr(2,2);
        }
	},
	formatLegendDate:function(tick,type){// type is frequency type.
		if(tick==null) return "";
		var t =  parseInt(tick,10),dt;
        if (type != "d"&&type!="w"&&type!="m") {
			dt = new Date(t);
            return (dt==null)?"": QS_DateFmt.getDatetimeString(dt);
        } else { 
			dt =  new Date (t* 86400000+new Date(1900,0,1).getTime());
            return (dt==null)?" " : QS_DateFmt.getDateString(dt);
        }
	},
	formateNumber:function(v,precision){
		return v==null||isNaN(v)?"--":QS_NumFmt.Fmt2(v,true,"",precision);
	},
	formatMDYDate:function(dt){
		return (dt==null)?" " : QS_DateFmt.getDateString(dt);//QS_DateFmt.Mo[dt.getMonth()]+" "+(dt.getDate()<10?"0"+dt.getDate():dt.getDate())+", "+dt.getFullYear();
	}
};
var RTQ_chartCustomDataBox = function(containerEl,cfg){
	this.option = {
		inputClassName:"qs-ui-ipt",
		width:62,
		splitLabel:"to",
		hoverColor:"#ffff99",
		startDate:null,
		endDate:null,
		callback:null,
		bindEvent:true
	}
	this.container = typeof(containerEl)=="String" ? $(containerEl):containerEl;
	this.inputBoxes;
	this._timeOut = null;
	this._isFocus = [false,false]  // if or not the two box is focused on.
	$.extend(this.option,cfg);
	this.init();
};
RTQ_chartCustomDataBox.prototype = {
	init:function(){
		var html = '<input type="text" class="'+this.option.inputClassName+'">';
		if(this.option.splitLabel){
			html += '<span class="rtc-ctrl-lb1">'+this.option.splitLabel+'</span>';
		}
		html += '<input type="text" class="'+this.option.inputClassName+'">';
		this.container.html(html);
		if(this.option.bindEvent){
			this.container.bind("mouseover.customBox",this,this.boxOnHover).bind("mouseout.customBox",this,this.boxOnOut);
			this.inputBoxes = $("input",this.container).bind("focus.customBox",this,this.boxOnFocus)
				.bind("blur.customBox",this,this.boxLoseFocus).bind("keydown.customBox",this,this.boxOnKeydown)
				.each(
					function(i){
		              $(this).data("index.customBox",i) // cache the index of box. 
		            }
				);
		}else{
			this.inputBoxes = $("input",this.container);
		}
		//this.inputBoxes.attr("readonly","readonly"); //readonly
		if(this.option.width){
			this.inputBoxes.css({width:this.option.width});
		}
		this.setDate(this.option.startDate,this.option.endDate);
	},
	boxOnHover:function(e){
		var self = e.data;
		self.inputBoxes.css({backgroundColor:self.option.hoverColor});
	},
	boxOnOut:function(e){
		var self = e.data;
		if(!self._isFocus[0]&&!self._isFocus[1]){
			self._checkDateChange();
		}
	},
	boxOnFocus:function(e){
		var self = e.data, index = $(e.target).data("index.customBox");
		if(self._timeOut!=null){
			clearTimeout(self._timeOut);
			self._timeOut = null;
		}
		self._isFocus[index] = true;
        var st = self.option.startDate, en = self.option.endDate;
        if (RTQ_ChartUtil.isVbDate(self.inputBoxes[0]["value"])) st = RTQ_ChartUtil.convertToVBDate(self.inputBoxes[0]["value"]);  //record the changed date
        if (RTQ_ChartUtil.isVbDate(self.inputBoxes[1]["value"])) en = RTQ_ChartUtil.convertToVBDate(self.inputBoxes[1]["value"]);  //record the changed date.
        var fv= (st == null) ? "" :(st.getMonth() + 1) + "/" + st.getDate() +"/" + st.getFullYear() ;
        var tv = (en == null) ? "" : (en.getMonth() + 1)+ "/" + en.getDate()+"/" + en.getFullYear();
        self.inputBoxes[0]["value"]= fv;
	    self.inputBoxes[1]["value"] = tv;
        if (document.all) {                         //ie move the foucs to end of text
            var esrc = e.srcElement;
            var rtextRange = esrc.createTextRange();
            rtextRange.moveStart('character', esrc.value.length);
            rtextRange.collapse(true);
            rtextRange.select();
        }
		
	},
	boxLoseFocus:function(e){
		var self = e.data, index = $(e.target).data("index.customBox");
		self._isFocus[index] = false;
		self._timeOut = setTimeout(function(){
			if(!self._isFocus[0]&& !self._isFocus[1]){ 
				self._checkDateChange();
			}
		},200);
	
	},
	boxOnKeydown:function(e){
		if(e.keyCode == 13){  // enter key down.
			//e.data._checkDateChange();
			$(e.target).trigger("blur");  // lose focus.
		}
	},
	_checkDateChange:function(){
        var frm = this.inputBoxes[0]["value"], tto = this.inputBoxes[1]["value"];
        if (RTQ_ChartUtil.isVbDate(frm) && RTQ_ChartUtil.isVbDate(tto) && RTQ_ChartUtil.compareDate(frm, tto)) {
            var ff = RTQ_ChartUtil.convertToVBDate(frm), tt = RTQ_ChartUtil.convertToVBDate(tto);
		 	st = this.option.startDate, en = this.option.endDate;
            if (st.getFullYear() == ff.getFullYear() && st.getMonth() == ff.getMonth() && st.getDate() == ff.getDate() && en.getFullYear() == tt.getFullYear() && en.getMonth() == tt.getMonth() && en.getDate() == tt.getDate()) {
                this._rollbackColor();
            }else{
				this.option.startDate = ff, this.option.endDate = tt;
				if(typeof(this.option.callback)=="function"){
					this.option.callback(this.option.startDate,this.option.endDate);
				}
			}
			this.inputBoxes.css({backgroundColor:""});
        } else {
            this._rollbackColor();
        }
	},
	_rollbackColor:function(){
		if (!this._isFocus[0]&& !this._isFocus[1]) {
            document.body.focus();
            this.inputBoxes.css({backgroundColor:""});
            if (document.activeElement.tagName.toUpperCase() != "INPUT") {
                   this.setDate(this.option.startDate,this.option.endDate);
            }
        }
	},
	setDate:function(startDate,endDate){
		if(startDate != null && endDate != null){
			this.option.startDate = startDate;
			this.option.endDate = endDate;
			this.inputBoxes[0]["value"]= QS_DateFmt.getDateString(startDate);
     		this.inputBoxes[1]["value"]= QS_DateFmt.getDateString(endDate);
		}else{
			 this.inputBoxes.val("");
		}
        
	},
	clear:function(){
		this.container.unbind(".customBox");
		this.inputBoxes.unbind(".customBox");
		this.container.remove();
		for(var p in this){
            if(!p || p == 'clear'){continue;}
            this[p] = null;
            delete this[p];
        }
	}
};
